package me.qingji.zebra.core.sync;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;

import me.qingji.zebra.bean.Article;
import me.qingji.zebra.bean.Chapter;

public class ArticleSync {

	private File home;

	public ArticleSync(File home) {
		this.home = home;
	}

	public ArticleSync(String path) {
		createHome(path);
	}

	public void sync(Article article) throws IOException {
		File file = new File(home, article.getLink().getName()+".txt");
		
		if(!file.exists()) {
			file.delete();
		}
		file.createNewFile();
		FileWriter writer = new FileWriter(file, true);
		try {
			List<Chapter> chapters = article.getChapters();
			for (int i = 0; i < chapters.size(); i++) {
				Chapter chapter = chapters.get(i);
				writer.write("\n\n\t章节 ："+chapter.getLink().getName()+"\n\n");
				writer.write(chapter.getText());
				writer.write("\n");
			}
		} finally {
			if (writer != null) {
				writer.close();
			}
		}

	}

	void createHome(String path) {
		home = new File(path);
		home.mkdirs();
	}

	public void setHome(File home) {
		this.home = home;
	}
}
